#!/usr/bin/env python
# coding=utf-8
# @FileName  :exception.py
# @Time      :2024/6/1 10:00
# @Author    :jdz
from fastapi import HTTPException, Request, status
from fastapi.responses import JSONResponse
from typing import Union
from fastapi.exceptions import RequestValidationError
from pydantic import ValidationError

from core.response import fail
from exception.base import CustomException
from util.mylog import my_logger


# 中间件异常之外的异常处理


async def http422_error_handler(
    _: Request,
    exc: Union[RequestValidationError, ValidationError],
) -> JSONResponse:
    """
    参数校验错误处理
    :param _:
    :param exc:
    :return:
    """
    my_logger.debug(f"[422]{exc.errors()}")
    return JSONResponse(
        content=fail(
            status.HTTP_422_UNPROCESSABLE_ENTITY, f"请求参数校验错误 {exc.errors()}"
        ),
        status_code=422,
    )


async def http_error_handler(_: Request, exc: HTTPException):
    """
    http异常处理
    :param _:
    :param exc:
    :return:
    """
    if exc.status_code == 400:
        return JSONResponse(
            fail(
                status.HTTP_400_BAD_REQUEST, "请求参数错误", {"error": str(exc.detail)}
            ),
            status_code=status.HTTP_400_BAD_REQUEST,
        )
    elif exc.status_code == 404:
        return JSONResponse(
            content=fail(status.HTTP_404_NOT_FOUND, "资源未找到"),
            status_code=status.HTTP_404_NOT_FOUND,
        )

    return JSONResponse(
        fail(exc.status_code, exc.detail, exc.detail),
        status_code=exc.status_code,
        headers=exc.headers,
    )


async def general_exception_handler(_: Request, e: Exception):
    my_logger.error(f"服务器内部错误 {e}")
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content=fail(status.HTTP_500_INTERNAL_SERVER_ERROR, "服务器内部错误"),
    )


async def custom_error_exp_handler(_: Request, exc: CustomException):
    return JSONResponse(
        content=fail(exc.status_code, exc.msg),
        status_code=exc.status_code,
    )
